package com.hskn.hss.module.workrule.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.workrule.entity.WorkRule;
import com.hskn.hss.module.workrule.entity.WorkRuleFull;
import com.hskn.hss.module.workrule.entity.WorkRuleFull2;
import com.hskn.hss.module.workrule.mapper.WorkRuleMapper;
import com.hskn.hss.module.workrule.service.IWorkRuleService;
import com.hskn.hss.module.workruleitem.entity.WorkRuleItem;
import com.hskn.hss.module.workruleitem.entity.WorkRuleItemFull2;
import com.hskn.hss.module.workruleitem.mapper.WorkRuleItemMapper;
import com.hskn.hss.module.workruleitem.service.IWorkRuleItemService;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-12
 */
@Service
public class WorkRuleServiceImpl extends ServiceImpl<WorkRuleMapper, WorkRule> implements IWorkRuleService {

    @Autowired
    private IWorkRuleItemService workRuleItemService;
    @Resource
    private WorkRuleMapper workRuleMapper;
    @Resource
    private WorkRuleItemMapper workRuleItemMapper;

    @Override
    @DataScope(deptAlias = "create_depid", userAlias = "create_uid, update_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<WorkRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(WorkRule::getCreateTime);
        String name = params.getString("name");
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.lambda().like(WorkRule::getRuleName, name);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(WorkRule::getModule, module);
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<WorkRule> workRulePage = new Page<>(page, size, true);
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        IPage<WorkRule> iPage = workRuleMapper.selectPage(workRulePage, queryWrapper);
        List<WorkRule> workRules = iPage.getRecords();
        List<WorkRuleFull2> workRuleFull2s = new ArrayList<>();
        for (WorkRule workRule : workRules) {
            QueryWrapper<WorkRuleItem> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(WorkRuleItem::getRuleId, workRule.getWorkRuleId());
            List<WorkRuleItem> ruleItems = workRuleItemMapper.selectList(queryWrapper1);
            List<WorkRuleItemFull2> workRuleItemFull2s = new ArrayList<>();
            for (WorkRuleItem ruleItem : ruleItems) {
                WorkRuleItemFull2 workRuleItemFull2 = new WorkRuleItemFull2();
                workRuleItemFull2.setContent(StringUtils.isEmpty(ruleItem.getContent()) ? new JSONObject() : JSONObject.parseObject(ruleItem.getContent()));
                workRuleItemFull2.setCustomName(ruleItem.getCustomName());
                workRuleItemFull2.setIsEnable(ruleItem.getIsEnable());
                workRuleItemFull2.setRemark(ruleItem.getRemark());
                workRuleItemFull2.setSysName(ruleItem.getSysName());
                workRuleItemFull2.setRuleId(ruleItem.getRuleId());
                workRuleItemFull2.setWorkRuleItemId(ruleItem.getWorkRuleItemId());
                workRuleItemFull2s.add(workRuleItemFull2);
            }
            WorkRuleFull2 workRuleFull2 = JSON.parseObject(JSON.toJSONString(workRule), WorkRuleFull2.class);
            workRuleFull2.setRuleItems(workRuleItemFull2s);
            workRuleFull2s.add(workRuleFull2);
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("workRules", workRuleFull2s);
        return json;
    }

    @Override
    @Transactional
    public void mUpdate(JSONObject params) throws HssException {
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("workRuleId"))) {
            throw new HssException("参数错误");
        }
        WorkRule workRule = JSON.parseObject(params.toJSONString(), WorkRule.class);
        workRuleMapper.updateById(workRule);
    }

    @Override
    @Transactional
    public void add(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        WorkRuleFull workRuleFull = JSON.parseObject(params.toJSONString(), WorkRuleFull.class);
        List<WorkRuleItem> ruleItems = workRuleFull.getRuleItems();
        if (StringUtils.isEmpty(ruleItems) || ruleItems.size() == 0) {
            throw new HssException("参数错误");
        }
        for (WorkRuleItem item : ruleItems) {
            try {
                JSONObject content = JSON.parseObject(item.getContent());
            } catch (Exception e) {
                throw new HssException("content 参数错误");
            }
        }
        WorkRule workRule = JSON.parseObject(params.toJSONString(), WorkRule.class);
        workRule.setCreateUid(uid);
        workRuleMapper.insert(workRule);
        for (WorkRuleItem ruleItem : ruleItems) {
            ruleItem.setRuleId(workRule.getWorkRuleId());
        }
        workRuleItemService.saveBatch(ruleItems);
    }

    @Override
    @Transactional
    public AjaxResult<Object> deleteJxqs(WorkRule workRule) throws HssException {
//        if (null != workRule) {
//            QueryWrapper<JxqsPlan> jxqsPlanQueryWrapper = new QueryWrapper<>();
//            jxqsPlanQueryWrapper.lambda().eq(JxqsPlan::getWorkRuleId, workRule.getWorkRuleId());
//            jxqsPlanQueryWrapper.lambda().le(JxqsPlan::getYxsdStart, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            jxqsPlanQueryWrapper.lambda().ge(JxqsPlan::getYxsdEnd, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            List<JxqsPlan> jxqsPlanList = jxqsPlanMapper.selectList(jxqsPlanQueryWrapper);
//            if (!jxqsPlanList.isEmpty()) {
//                return AjaxResult.success("此规则已被机械清扫占用，删除会导致数据错误");
//            } else {
//                workRuleMapper.deleteById(workRule.getWorkRuleId());
//            }
//        }
        return AjaxResult.success("删除成功");
    }

    @Override
    @Transactional
    public AjaxResult<Object> deleteLjqy(WorkRule workRule) throws HssException {
//        if (null != workRule) {
//            QueryWrapper<LjqyWorkPlan> ljqyWorkPlanQueryWrapper = new QueryWrapper<>();
//            ljqyWorkPlanQueryWrapper.lambda().eq(LjqyWorkPlan::getWorkRuleId, workRule.getWorkRuleId());
//            ljqyWorkPlanQueryWrapper.lambda().le(LjqyWorkPlan::getYxsdStartDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            ljqyWorkPlanQueryWrapper.lambda().ge(LjqyWorkPlan::getYxsdEndDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            List<LjqyWorkPlan> jljqyWorkPlanList = ljqyWorkPlanMapper.selectList(ljqyWorkPlanQueryWrapper);
//            if (!jljqyWorkPlanList.isEmpty()) {
//                return AjaxResult.success("此规则已被垃圾清运占用，删除会导致数据错误");
//            } else {
//                workRuleMapper.deleteById(workRule.getWorkRuleId());
//            }
//        }
        return AjaxResult.success("删除成功");
    }

    @Override
    @Transactional
    public AjaxResult<Object> deleteLjzy(WorkRule workRule) throws HssException {
//        if (null != workRule) {
//            QueryWrapper<LjzyWorkPlan> ljzyWorkPlanQueryWrapper = new QueryWrapper<>();
//            ljzyWorkPlanQueryWrapper.lambda().eq(LjzyWorkPlan::getWorkRuleId, workRule.getWorkRuleId());
//            ljzyWorkPlanQueryWrapper.lambda().le(LjzyWorkPlan::getYxsdStartDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            ljzyWorkPlanQueryWrapper.lambda().ge(LjzyWorkPlan::getYxsdEndDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            List<LjzyWorkPlan> ljzyWorkPlanList = ljzyWorkPlanMapper.selectList(ljzyWorkPlanQueryWrapper);
//            if (!ljzyWorkPlanList.isEmpty()) {
//                return AjaxResult.success("此规则已被垃圾转运占用，删除会导致数据错误");
//            } else {
//                workRuleMapper.deleteById(workRule.getWorkRuleId());
//            }
//        }
        return AjaxResult.success("删除成功");
    }

    @Override
    @Transactional
    public AjaxResult<Object> deleteDlbj(WorkRule workRule) throws HssException {
        if (null != workRule) {
//            QueryWrapper<WorkPlan> workPlanQueryWrapper = new QueryWrapper<>();
//            workPlanQueryWrapper.lambda().eq(WorkPlan::getRuleId, workRule.getWorkRuleId());
//            workPlanQueryWrapper.lambda().le(WorkPlan::getStartDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            workPlanQueryWrapper.lambda().ge(WorkPlan::getEndDate, DateUtil.format(new Date(), "yyyy-MM-dd"));
//            List<WorkPlan> workPlanList = workPlanMapper.selectList(workPlanQueryWrapper);
//            if (!workPlanList.isEmpty()) {
//                return AjaxResult.success("此规则已被道路保洁占用，删除会导致数据错误");
//            } else {
//                workRuleMapper.deleteById(workRule.getWorkRuleId());
//            }
        }
        return AjaxResult.success("删除成功");
    }

    @Override
    public WorkRuleFull2 detail(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("workRuleId"))) {
            throw new HssException("参数错误");
        }
        WorkRule workRule = workRuleMapper.selectById(params.getString("workRuleId"));
        QueryWrapper<WorkRuleItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WorkRuleItem::getRuleId, workRule.getWorkRuleId());
        List<WorkRuleItem> ruleItems = workRuleItemMapper.selectList(queryWrapper);
        WorkRuleFull2 workRuleFull2 = JSON.parseObject(JSON.toJSONString(workRule), WorkRuleFull2.class);
        List<WorkRuleItemFull2> ruleItemFull2s = new ArrayList<>();
        for (WorkRuleItem ruleItem : ruleItems) {
            WorkRuleItemFull2 workRuleItemFull2 = new WorkRuleItemFull2();
            workRuleItemFull2.setContent(StringUtils.isEmpty(ruleItem.getContent()) ? new JSONObject() : JSONObject.parseObject(ruleItem.getContent()));
            workRuleItemFull2.setCustomName(ruleItem.getCustomName());
            workRuleItemFull2.setIsEnable(ruleItem.getIsEnable());
            workRuleItemFull2.setRemark(ruleItem.getRemark());
            workRuleItemFull2.setSysName(ruleItem.getSysName());
            workRuleItemFull2.setRuleId(ruleItem.getRuleId());
            workRuleItemFull2.setWorkRuleItemId(ruleItem.getWorkRuleItemId());
            workRuleItemFull2.setPolymerizationtime(ruleItem.getPolymerizationtime());
            ruleItemFull2s.add(workRuleItemFull2);
        }
        workRuleFull2.setRuleItems(ruleItemFull2s);
        return workRuleFull2;
    }

}
